<?php

namespace app\common\controller;

use app\common\model\Teacher;
use think\Cache;
use think\Hook;
use think\Request;

class BaseController extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    protected $teacherId;

    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        if ($request->module() === 'teacher') {
            $this->teacherToken();
        }
    }

    /**
     * 单参数验证
     * @param mixed $str
     */
    public function notEmpty($str)
    {
        $param = $this->request->param($str);
        return empty($param) ? $this->error($str . '不能为空') : $param;
    }

    /**
     * 没有数据
     */
    public function notFoundData($msg = '暂无数据')
    {
        $this->result($msg, null, 405, null, []);
    }

    /**
     * 数据更新、添加等失败
     */
    public function forbidden($msg = '拒绝访问')
    {
        $this->result($msg, null, 403, null, []);
    }

    /**
     * 不是POST请求
     */
    public function isPost()
    {
        return $this->request->isPost() ? true : $this->result('请使用POST请求', null, 404, null, []);
    }

    /**
     * 错误信息
     * @param int $code
     * @param null $data
     */
    public function errorMsg($code = 0, $data = null)
    {
        $msg = isset(config('errorMessage')[$code]) ? config('errorMessage')[$code] : '';
        $this->error($msg, $data, $code);
    }

    /**
     * 参数验证
     */
    public function paramValidate($validate, $param)
    {
        if (!$validate->batch()->check($param)) {
            foreach ($validate->getError() as $val) {
                $this->error($val);
            }
        }
        return true;
    }

    /**
     * 验证教师端登录
     */
    public function teacherToken()
    {
//        $this->teacherId = 1;
//        return true;
        $actions = ['auth', 'decrypt', 'create', 'sign', 'agreement'];
        $controllers = ['V1.user', 'V1.oss'];
        $controller = $this->request->controller();
        $action = $this->request->action();
        if (!in_array($controller, $controllers) || !in_array($action, $actions)) {
            $request = Request::instance();
            $token = $request->header('teachertoken');
            if (!$token) {
                $this->errorMsg(402);
            }
            $teacherId = Cache::get('teacher_token_'.$token);
            if (!$teacherId) {
                $teacher = Teacher::where('token', $token)->find();
                if (!$teacher) {
                    $this->errorMsg(993);
                }
                Cache::set('teacher_token_'.$token, $teacher->teacher_id, 2592000);
                $teacherId = $teacher->teacher_id;
            }
            $this->teacherId = $teacherId;
        }

        return true;
    }


}
